import { requestUtil } from '../../utils/requestUtil.js';

Page({
    /**
     * 页面的初始数据
     */
    data: {
        regionText: "",
        addressId: null, // 用于存储要修改的地址id
        addressData: {}, // 用于存储要修改的地址数据
        isDefaultChecked: false // 用于存储设为默认地址的开关状态，初始为false
    },

    regionChange(e) {
        const text = e.detail.value.join("");
        this.setData({
            regionText: text
        });
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        if (options.id) {
            // 如果有id参数，说明是修改地址
            this.setData({
                addressId: options.id
            });
            this.getAddressData(options.id);
        }
    },

    getAddressData(id) {
        const app = getApp();
        let openid = wx.getStorageSync('openid');
        if (!openid) {
            openid = app.globalData.openid;
        }
        if (!openid) {
            wx.showToast({
                title: '获取用户标识失败，请重新登录',
                icon: 'none'
            });
            return;
        }
        requestUtil({
            url: `/address/detail/${id}`, // 假设后端有获取单个地址的接口
            method: 'GET'
        }).then(result => {
            console.log('获取地址详情结果:', result);
            this.setData({
                addressData: result.data,
                regionText: result.data.address,
                userName: result.data.userName,
                telNumber: result.data.telNumber,
                detailInfo: result.data.detailInfo,
                // 将isDefault转换为布尔类型
                isDefaultChecked: result.data.isDefault === 1
            });
        }).catch(err => {
            console.log('获取地址详情出错:', err);
            wx.showToast({
                title: '获取地址详情失败',
                icon: 'none'
            });
        });
    },

    formSubmit(e) {
        const formData = e.detail.value;
        const app = getApp();
        let openid = wx.getStorageSync('openid');
        if (!openid) {
            openid = app.globalData.openid;
        }
        if (!openid) {
            wx.showToast({
                title: '获取用户标识失败，请重新登录',
                icon: 'none'
            });
            return;
        }
        formData.openid = openid;
        // 将 regionText 的值赋值给 formData.address
        formData.address = this.data.regionText;

        // 确保 isDefault 是数字类型
        formData.isDefault = this.data.isDefaultChecked? 1 : 0;

        if (this.data.addressId) {
            // 修改地址
            formData.id = this.data.addressId;
            requestUtil({
                url: '/address/update',
                method: 'POST',
                data: formData
            }).then(result => {
                console.log('修改地址结果:', result);
                wx.showToast({
                    title: '修改地址成功',
                    icon:'success'
                });
                wx.navigateBack();
                this.getAddressList();
            }).catch(err => {
                console.log('修改地址出错:', err);
                wx.showToast({
                    title: '修改地址失败',
                    icon: 'none'
                });
            });
        } else {
            // 添加地址
            requestUtil({
                url: '/address/add',
                method: 'POST',
                data: formData
            }).then(result => {
                console.log('添加地址结果:', result);
                wx.showToast({
                    title: '添加地址成功',
                    icon:'success'
                });
                wx.navigateBack();
                this.getAddressList();
            }).catch(err => {
                console.log('添加地址出错:', err);
                wx.showToast({
                    title: '添加地址失败',
                    icon: 'none'
                });
            });
        }
    },

    getAddressList: function () {
        const app = getApp();
        let openid = wx.getStorageSync('openid');
        if (!openid) {
            openid = app.globalData.openid;
        }
        if (!openid) {
            wx.showToast({
                title: '获取用户标识失败，请重新登录',
                icon: 'none'
            });
            return;
        }
        requestUtil({
            url: '/address/list/' + openid,
            method: 'GET'
        }).then(result => {
            console.log('获取地址列表结果:', result);
            const processedAddressList = result.data.map(item => {
                if (item.userName) {
                    item.userName = item.userName.replace(/&nbsp;/g, ' ');
                }
                return item;
            });
            this.setData({
                addressList: processedAddressList
            });
        }).catch(err => {
            console.log('获取地址列表出错:', err);
            wx.showToast({
                title: '获取地址列表失败',
                icon: 'none'
            });
        });
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})